import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userdata:'',
    userRole:[],
    userId:''
  }
}

const state = getDefaultState()



const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    console.log(state.token)
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_DATA:(state,data)=>{
    state.userdata = data
    localStorage.setItem("userMsg",JSON.stringify(state.userdata))
    console.log(state.userdata)
    

  },
  SET_USERROLE:(state,data)=>{
    state.userRole = data
    localStorage.setItem("userRole",JSON.stringify(state.userRole))
    console.log("1111")

  }

}

const actions = {
  // user login
  //第一个结构commit是什么意思
  // 从上下文中拿到commit 执行mutation
  //花括号里面的commit代表什么 就是context.commit
  login({ commit }, userInfo) {
        const { loginName, password } = userInfo
        return new Promise((resolve, reject) => {
          login({ loginName: loginName.trim(), password: password }).then(response => {
    //         console.log(response)
            const { data } = response
            console.log(data.menus);
            localStorage.setItem('menu',JSON.stringify(data.menus))
            
            commit('SET_TOKEN', data.token)
            setToken(data.token)
            commit('SET_NAME', data.username)
            commit('SET_DATA',data)
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },

  // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const { data } = response

  //       if (!data) {
  //         return reject('Verification failed, please Login again.')
  //       }

  //       const { name, avatar } = data

  //       commit('SET_NAME', name)
  //       commit('SET_AVATAR', avatar)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // user logout
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
          removeToken() // must remove  token  first
          resetRouter()
          commit('RESET_STATE')
          resolve()
        })
      },

  // remove token
  resetToken({ commit }) {
        console.log('resetToken');
        return new Promise(resolve => {
          removeToken() // must remove  token  first
          commit('RESET_STATE')
          resolve()
        })
      }
    }

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

